package com.pureut.system.service.impl;

import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.MaterialCoding;
import com.pureut.system.domain.MaterialWaste;
import com.pureut.system.domain.dto.MaterialMqDto;
import com.pureut.system.domain.dto.MaterialWasteDto;
import com.pureut.system.domain.dto.ProjectRecursionDto;
import com.pureut.system.domain.vo.MaterialWasteVo;
import com.pureut.system.export.MaterialWasteExport;
import com.pureut.system.mapper.MaterialCodingMapper;
import com.pureut.system.mapper.MaterialWasteMapper;
import com.pureut.system.service.IMaterialWasteService;
import com.pureut.system.util.MaterialMqUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 废料信息实现类
 * @Param
 * @Date 22-11-25
 * @Author hl
 **/
@Service
public class MaterialWasteServiceImpl implements IMaterialWasteService {
    @Resource
    private MaterialWasteMapper materialWasteMapper;

    @Resource
    private MaterialCodingMapper materialCodingMapper;

    @Resource
    private SysMidSplitServiceImpl sysMidSplitServiceImpl;

    /**
     * 查询废料信息
     *
     * @param materialWaste 废料信息
     * @return 废料信息集合
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<MaterialWasteDto> selectWasteList(MaterialWasteVo materialWaste) {
        List<SysDictData> netArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<MaterialWasteDto> list = materialWasteMapper.selectWasteList(materialWaste);
        for (MaterialWasteDto dto :
                list) {
            dto.setMaterialUnitDict(netMap.get(String.valueOf(dto.getMaterialUnit())));
        }
        return list;
    }

    /**
     * 新增废料信息
     *
     * @param materialWaste 废料信息
     * @return 废料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertWaste(MaterialWaste materialWaste) throws Exception {
        materialWaste.setDeptId(SecurityUtils.getDeptId());
        materialWaste.setMaterialCode(sysMidSplitServiceImpl.splitStr(materialCodingMapper.selectCodingTypeThe(materialWaste.getMaterialType())));
        materialWaste.setCreateBy(SecurityUtils.getUsername());
        //mq发送消息
        MaterialMqDto mq = new MaterialMqDto();
        mq.setMaterialCode(materialWaste.getMaterialCode());
        mq.setMaterialName(materialWaste.getMaterialName());
        mq.setMaterialSpec(materialWaste.getMaterialSpec());
        mq.setMaterialCategory(5);
        mq.setMaterialType(materialWaste.getMaterialType());
        mq.setMaterialUnit(String.valueOf(materialWaste.getMaterialUnit()));
        mq.setMaterialHair(materialWaste.getMaterialHair());
        mq.setMaterialClosed(materialWaste.getMaterialClosed());
        MaterialMqUtil.materialMqSend(mq);
        return materialWasteMapper.insertWaste(materialWaste);
    }

    /**
     * 删除辅料信息
     *
     * @param materialId 辅料信息ID
     * @return 辅料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteWasteById(String materialId) throws Exception {
        String[] materialIdS = materialId.split(",");
        //同步删除废料信息
        MaterialMqDto mq = new MaterialMqDto();
        List<String> materialIdList = Arrays.asList(materialId.split(","));
        String strCode = materialWasteMapper.getStrWasteById(materialIdList);
        mq.setMaterialCode(strCode);
        //删除标识
        mq.setMark(3);
        MaterialMqUtil.materialMqSendDelete(mq);

        int is = materialWasteMapper.deleteWasteById(materialIdS);

        return is;
    }

    /**
     * 查询单个废料信息
     *
     * @param materialId 废料信息ID
     * @return 废料信息集合
     */
    @Override
    public MaterialWasteDto selectWasteById(long materialId) {
        MaterialWasteVo materialWaste = new MaterialWasteVo();
        materialWaste.setMaterialId(materialId);
        List<MaterialWasteDto> list = materialWasteMapper.selectWasteList(materialWaste);
        MaterialWasteDto materialWasteDto = list.get(0);
        List<SysDictData> dictList = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> actualMap = dictList.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        materialWasteDto.setMaterialUnitDict(actualMap.get(materialWasteDto.getMaterialUnit()));
        return materialWasteDto;
    }

    /**
     * 修改废料信息
     *
     * @param materialWaste 废料信息
     * @return 废料信息集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMateriaWasteEdit(MaterialWaste materialWaste) throws Exception {
        //mq发送消息
        MaterialMqDto mq = new MaterialMqDto();
        mq.setMaterialCode(materialWaste.getMaterialCode());
        mq.setMaterialName(materialWaste.getMaterialName());
        mq.setMaterialSpec(materialWaste.getMaterialSpec());
        mq.setMaterialCategory(5);
        mq.setMaterialType(materialWaste.getMaterialType());
        mq.setMaterialUnit(String.valueOf(materialWaste.getMaterialUnit()));
        mq.setMaterialHair(materialWaste.getMaterialHair());
        mq.setMaterialClosed(materialWaste.getMaterialClosed());
        MaterialMqUtil.materialMqSend(mq);
        return materialWasteMapper.updateMateriaWasteEdit(materialWaste);
    }

    /**
     * 冻结/解冻
     *
     * @param materialWaste 废料信息
     * @return 废料信息集合
     */
    @Override
    public int updateWasteEditFreeze(MaterialWaste materialWaste) {
        return materialWasteMapper.updateWasteEditFreeze(materialWaste);
    }

    /**
     * 树结构
     *
     * @param
     * @return
     */
    @Override
    public List<ProjectRecursionDto> selectChildrenWasteThe() {
        return MaterialAwmateriaServiceImpl.buildMenuTree(materialWasteMapper.selectChildrenWasteThe());
    }

    /**
     * 导入
     *
     * @param coCustomer
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMouldData(List<MaterialWasteExport> coCustomer) {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入废料信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        //物料单位
        List<SysDictData> netArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (MaterialWasteExport mouldModelExport : coCustomer) {
            MaterialWaste materialWaste = new MaterialWaste();
            try {

                if (mouldModelExport.getMaterialName()==null||"".equals(mouldModelExport.getMaterialName())){
                    throw new GlobalException("物料名称不能为空");
                }

                if (mouldModelExport.getMaterialUnit()==null||"".equals(mouldModelExport.getMaterialUnit())){
                    throw new GlobalException("物料单位不能为空");
                }

                //名称
                materialWaste.setMaterialName(mouldModelExport.getMaterialName());
                //规格
                if (mouldModelExport.getMaterialSpec() != null) {
                    materialWaste.setMaterialSpec(mouldModelExport.getMaterialSpec());
                } else {
                    materialWaste.setMaterialSpec("");
                }
                //类别（先查询填写的该类别是否存在）
                MaterialCoding typeByName = materialCodingMapper.getTypeByName(mouldModelExport.getMaterialType());
                if (typeByName != null) {
                    materialWaste.setMaterialType((int) typeByName.getCodingId());
                } else {
                    throw new GlobalException("该类别不存在，请核实");
                }
                //编码
//                materialWaste.setMaterialCode(sysMidSplitServiceImpl.splitStr(typeByName.getCodingOf()));
                //单位
                for (Map.Entry<String, String> entry : netMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getMaterialUnit())) {
                        materialWaste.setMaterialUnit(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }
                //超收标志
                if ("开".equals(mouldModelExport.getMaterialClosed())) {
                    materialWaste.setMaterialClosed(1);
                } else {
                    materialWaste.setMaterialClosed(2);
                }
                //超发标志
                if ("开".equals(mouldModelExport.getMaterialHair())) {
                    materialWaste.setMaterialHair(1);
                } else {
                    materialWaste.setMaterialHair(2);
                }
                //创建人
                materialWaste.setCreateBy(SecurityUtils.getUsername());
                materialWaste.setDeptId(SecurityUtils.getDeptId());
                insertWaste(materialWaste);

                successNum++;
                successMsg.append(successNum + "、废料信息 " + mouldModelExport.getMaterialName() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、废料 " + mouldModelExport.getMaterialName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
